package com.temp.controller.admin;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.temp.dto.ChatMessageDTO;
import com.temp.dto.SearchChatDTO;
import com.temp.entity.ChatMessage;
import com.temp.result.Result;
import com.temp.service.ChatMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/admin/chat")
@Api(tags = "管理聊天相关的接口")
@Slf4j
@Validated
public class AdminChatController {

    @Autowired
    private ChatMessageService chatMessageService;

    @PostMapping("/query")
    @ApiOperation("管理员获取聊天记录")
    @RequiresPermissions("admin:chat:query")
    public Result getAllChat(@RequestBody SearchChatDTO chatDTO) {
        chatDTO.formatParam();
        return Result.success(chatMessageService.findALlUserChat(chatDTO),"apiMsg.querySuccess");
    }

    @GetMapping("/queryById")
    @ApiOperation("用户Id获取聊天记录")
    @RequiresPermissions("admin:chat:queryById")
    public Result getHistoryById(@RequestParam("userId") String userId) {
        List<ChatMessage> list = chatMessageService.list(Wrappers.<ChatMessage>lambdaQuery()
                .eq(ChatMessage::getSenderId, userId)
                .or()
                .eq(ChatMessage::getReceiverId, userId)
                .orderByAsc(ChatMessage::getCreatedAt));
        chatMessageService.update(
                new LambdaUpdateWrapper<ChatMessage>()
                        .eq(ChatMessage::getStatus, "SENT")
                        .eq(ChatMessage::getSenderId, userId)
                        .set(ChatMessage::getStatus, "READ")
        );
        return Result.success(list, "apiMsg.querySuccess");
    }

    @PostMapping("/add")
    @ApiOperation("管理员保存消息")
    @RequiresPermissions("admin:chat:add")
    public Result addChatMessage(@Valid @RequestBody ChatMessageDTO chatMessageDTO) {
        ChatMessage chatMessage = new ChatMessage();
        BeanUtils.copyProperties(chatMessageDTO,chatMessage);
        boolean isSuccess = chatMessageService.save(chatMessage);

        return isSuccess ? Result.success(chatMessage,"apiMsg.optionSuccess") : Result.error("apiMsg.optionError");
    }
}
